import { createRouter, createWebHistory } from 'vue-router';
import { useUserStore } from '../stores/user';
import { ElMessage } from 'element-plus';
import AdminPage from '../pages/AdminPage.vue'; // 直接导入管理页面组件

const routes = [
  {
    path: '/',
    component: () => import('../layouts/DefaultLayout.vue'),
    redirect: '/home',
    children: [
      {
        path: 'home',
        name: 'Home',
        component: () => import('../pages/HomePage.vue'),
        meta: { title: '首页', requiresAuth: false }
      },
      {
        path: 'questions',
        name: 'QuestionList',
        component: () => import('../pages/QuestionList.vue'),
        meta: { title: '问题列表', requiresAuth: false }
      },
      {
        path: 'questions/:id',
        name: 'QuestionDetail',
        component: () => import('../pages/QuestionDetailPage.vue'),
        meta: { title: '问题详情', requiresAuth: false }
      },
      {
        path: 'ask',
        name: 'AskQuestion',
        component: () => import('../pages/AskQuestionPage.vue'),
        meta: { title: '提问题', requiresAuth: true }
      },
      {
        path: 'user/:id',
        name: 'UserProfile',
        component: () => import('../pages/UserProfile.vue'),
        meta: { title: '用户主页', requiresAuth: false }
      },
      {
        path: 'my-profile',
        redirect: to => {
          const userStore = useUserStore();
          if (userStore.userInfo) {
            return { path: `/user/${userStore.userInfo.id}` };
          }
          return { path: '/login' };
        },
        meta: { requiresAuth: true }
      },
      {
        path: 'settings',
        name: 'Settings',
        component: () => import('../pages/SettingsPage.vue'),
        meta: { title: '个人设置', requiresAuth: true }
      },
      {
        path: 'search',
        name: 'Search',
        component: () => import('../pages/SearchPage.vue'),
        meta: { title: '搜索结果', requiresAuth: false }
      },
      {
        path: 'notifications',
        name: 'Notifications',
        component: () => import('../pages/NotificationsPage.vue'),
        meta: { title: '我的通知', requiresAuth: true }
      },
      {
        path: 'admin',
        name: 'AdminPage',
        component: AdminPage, // 使用直接导入的组件替代懒加载
        meta: { title: '管理后台', requiresAuth: true, requiredRole: 'ADMIN' }
      }
    ]
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('../pages/LoginPage.vue'),
    meta: { title: '登录', requiresAuth: false }
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('../pages/RegisterPage.vue'),
    meta: { title: '注册', requiresAuth: false }
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('../pages/NotFound.vue')
  }
];

const router = createRouter({
  history: createWebHistory(),
  routes
});

// 全局导航守卫
router.beforeEach(async (to, from, next) => {
  // 设置页面标题
  document.title = to.meta.title ? `${to.meta.title} - 智问社区` : '智问社区';
  
  const userStore = useUserStore();
  
  // 先尝试获取用户信息（如果有token但还没有用户信息）
  if (!userStore.userInfo && localStorage.getItem('token')) {
    try {
      await userStore.fetchUserInfo();
    } catch (error) {
      console.error('获取用户信息失败:', error);
      // 清除无效token
      localStorage.removeItem('token');
    }
  }
  
  // 判断页面是否需要登录权限
  if (to.meta.requiresAuth) {
    // 判断是否已登录
    if (!userStore.isLogin) {
      ElMessage.warning('请先登录');
      next({ name: 'Login', query: { redirect: to.fullPath } });
      return;
    }
    
    // 判断是否有所需角色权限
    if (to.meta.requiredRole) {
      // 将数字角色映射为角色名称
      const roleMap = {
        1: 'NORMAL',
        2: 'EXPERT',
        3: 'ADMIN'
      };
      const userRole = roleMap[userStore.userInfo?.role] || '';
      
      if (userRole !== to.meta.requiredRole) {
        ElMessage.error('您没有权限访问该页面');
        next('/');
        return;
      }
    }
  } else if (to.path === '/login' && userStore.isLogin) {
    // 如果已登录且访问登录页，重定向到首页
    next('/');
    return;
  }
  
  next();
});

export default router; 